import express from "express";
import multer from "multer";
import { appendFile, readFile, rm } from "node:fs/promises";
import { resolve } from "node:path";

const uploadDir = "./service/upload";
const fileDir = "./service/file";

const upload = multer({ dest: uploadDir });
const router = express.Router();


router.post("/upload", upload.single("file"), (req, res) => {
  console.log(req.file);
  const time = new Date().getTime() + ".json";
  const json = JSON.stringify(req.file);
  appendFile(resolve(fileDir, time), json);
  res.send({
    code: 20000,
    msg: "上传成功;",
    data: time
  });
});

router.post("/download/:name", (req, res) => {
  const name = req.params.name;
  console.log("name:", name);
  const filePath = resolve(fileDir, name);
  readFile(filePath, { encoding: "utf8" }).then(content => {
    const { originalname, filename } = JSON.parse(content);
    res.send({
      code: 20000,
      msg: "",
      data: {
        originalname,
        filename
      }
    });
  });
});

router.post("/getFile/:file", (req, res) => {
  const name = req.params.file;
  res.sendFile(resolve(uploadDir, name));
});

router.post("/delete/:name", (req, res) => {
  const name = req.params.name;
  console.log("name:", name);
  const filePath = resolve(fileDir, name);
  readFile(filePath, { encoding: "utf8" }).then(content => {
    const { filename } = JSON.parse(content);
    rm(resolve(uploadDir, filename)).then(() => {
      rm(resolve(fileDir, name)).then(() => {
        res.send({
          code: 20000,
          msg: "删除成功！",
          data: null
        });
      });
    });
  });
});

export default router;
